package com.zhongshengnetwork.rightbe.letter.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
//import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.core.app.ActivityCompat;

import com.huantansheng.easyphotos.EasyPhotos;
import com.sj.emoji.EmojiBean;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DateUtil;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.HandlerDefine;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.ReportActivity;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.pulluprefresh.xlistview.XListView;
import com.zhongshengnetwork.rightbe.dbmodel.LetterdbModel;
import com.zhongshengnetwork.rightbe.dbmodel.PeopledbModel;
import com.zhongshengnetwork.rightbe.dbservice.LetterdbService;
import com.zhongshengnetwork.rightbe.dbservice.PeopledbService;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.SXSendResult;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.keyboard.Constants;
import com.zhongshengnetwork.rightbe.keyboard.LjxEmoticonsKeyBoard;
import com.zhongshengnetwork.rightbe.keyboard.SimpleCommonUtils;
import com.zhongshengnetwork.rightbe.keyboard.widget.SimpleAppsGridView;
import com.zhongshengnetwork.rightbe.letter.adapter.ChatViewAdapter;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.GlideEngine;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//import me.iwf.photopicker.PhotoPicker;
//import me.iwf.photopicker.PhotoPickerActivity;
//import me.iwf.photopicker.utils.PhotoPickerIntent;
import sj.keyboard.data.EmoticonEntity;
import sj.keyboard.interfaces.EmoticonClickListener;
import sj.keyboard.utils.EmoticonsKeyboardUtils;
import sj.keyboard.widget.EmoticonsEditText;
import sj.keyboard.widget.FuncLayout;

//三检查OK:2016-11-30
public class ChatViewActivity extends AppBaseActivity implements FuncLayout.OnFuncKeyBoardListener, TopBarView.onTitleBarClickListener,View.OnClickListener{
    private static final int SCALE = 5;
    private static final int TAKE_PICTURE = 1000;//拍照
    private static final int CHOOSE_PICTURE = 1001;//选择图片
    private static final int CHOOSE_CARD = 1002;//选择名片
    private static final int CHOOSE_GOODS = 1003;//选择商品
    private static final int Private_Red = 1004;//私人红包
    private static final int Common_Red = 1005;//普通红包
    private static final int Rand_Red = 1006;//拼手气红包
    private static final int Guess_Red = 1007;//猜猜红包
    private static final int Prize_Red = 1008;//抽奖红包
    private static final int Select_Location = 1009;//选择地理位置
    private static final int At_Message = 1010;//选择@信息
    public static final int UserInfo = 1011;//用户信息
    public static final int Update_Pic = 1012;//更新了表情
    public static int lastPlayIndex = -1;
    private ChatViewAdapter chattingListAdapter;
    private TopBarView topbar;
    private XListView lvChat;
    private LjxEmoticonsKeyBoard ekBar;
    private LetterdbModel target;
    private String targetId;
    private MyHandler myHandler;
    private View animView;
    private int oldestMessageId = 0;
    private LinearLayout myChatView;


    private String sendPicUrl;

    //菜单
    private PopupWindow popWindow;

    private ClipboardManager myClipboard;
    private ClipData myClip;
    private long lastMessageTime = System.currentTimeMillis();

    private String createMessage;

    private RelativeLayout moreMessage;
    private Button moreButton;
    private int scrollIndex = 0;
    private int newCount = 0;
    private int pageIndex = 0;


    private LinearLayout my_chat_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //注册广播
        registerBoradcastReceiver();
        setContentView(R.layout.activity_chat_view);
        myHandler = new MyHandler();
        myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
        target = (LetterdbModel)getIntent().getSerializableExtra("model");
        if(target != null){
            LetterdbService.changeToSendFailState(target.getUserid(), target.getFromuserid());
        }
        newCount = getIntent().getIntExtra("newCount", 0);
        createMessage = target.getNickname();
        targetId = target.getFromuserid();
        String title = target.getNickname();
        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(LetterConstant.InChatKey, targetId);


        topbar = (TopBarView)findViewById(R.id.chatview_toolbar);
        topbar.getRightView().setImageResource(R.drawable.more);
        topbar.getRightView().setClickable(true);
        topbar.getRightView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final List<String> menu = new ArrayList<String>();
                menu.add("举报");
                PeopledbModel p = PeopledbService.getOneData(target.getUserid(), target.getFromuserid());
                if (p != null && p.getType() == LetterConstant.sx_black_people){
                    menu.add("从黑名单移除");
                }else {
                    menu.add("加入黑名单");
                }
                menu.add("清除所有私信记录");
                ActionSheetDialog actionSheetDialog = new ActionSheetDialog(ChatViewActivity.this)
                        .builder()
                        .setTitle("")
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(true);
                for (String m : menu){
                    actionSheetDialog.addSheetItem(m, null, new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            if (which == 1){
                                report(target.getFromuserid(), 1);
                            }else if (which == 2){
                                String state = "0";
                                if (menu.get(1).equals("加入黑名单")){
                                    state = "1";
                                }
                                black(state);
                            }else if (which == 3){
                                LetterdbService.deleteChat(target.getUserid(), target.getFromuserid());
                                chattingListAdapter.clearData();
                            }
                        }
                    });
                }
                actionSheetDialog.show();
            }
        });
        topbar.getTitleView().setText(title);
        topbar.setClickListener(this);
        ekBar = (LjxEmoticonsKeyBoard) findViewById(R.id.chatview_ek_bar);
        //ekBar.getBtnVoice().setVisibility(View.GONE);
        lvChat = (XListView) findViewById(R.id.chatview_listview);

        lvChat.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                    case MotionEvent.ACTION_UP:
                        if (ekBar != null){
                            ekBar.reset();
                        }
                        break;
                }
                return false;
            }
        });

        initView();

        lvChat.setPullLoadEnable(false);
        lvChat.setPullRefreshEnable(true);
        lvChat.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                lvChat.setRefreshTime(sdf.format(date));
                loadMore();
            }

            @Override
            public void onLoadMore() {

            }
        });
        moreMessage = (RelativeLayout) findViewById(R.id.more_message_view);
        moreMessage.setVisibility(View.INVISIBLE);
        moreButton = (Button) findViewById(R.id.more_button);
        moreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //System.out.print("更多\n");
                lvChat.requestLayout();
                lvChat.post(new Runnable() {
                    @Override
                    public void run() {
                        moreMessage.setVisibility(View.INVISIBLE);
                        lvChat.setSelection(scrollIndex);
                    }
                });
            }
        });

        
        lvChat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.print("点击了setOnItemClickListener\n");
                LetterdbModel chatData = chattingListAdapter.getIndexData(position-1);
                if (chatData != null){
                    
                }
            }
        });

        lvChat.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //System.out.print("长按聊天\n");
                LetterdbModel chatData = chattingListAdapter.getIndexData(position-1);
                if (chatData == null || chatData.getType() == LetterConstant.sx_timeMsg || chatData.getType() == LetterConstant.sx_unDefineMsg){
                    return true;
                }

                if (chatData.getState() == LetterConstant.sx_sending_state){//非成功消息不处理
                    return true;
                }
                List<String> names = new ArrayList<String>();
                if (chatData.getIsSelf() == 1){
                    if (chatData.getState() == LetterConstant.sx_normal_state){
                        if (System.currentTimeMillis() - chatData.getTime() <= LetterConstant.sx_msg_timeout){
                            names.add("撤回");
                        }
                    }
                }
                if (chatData.getType() == LetterConstant.sx_textMsg){//文本消息
                    names.add("复制");
                }
                names.add("删除");
                popWindow(view, names, position-1);

                return true;
            }
        });


    }

    private void report(String reportId, int reportType){//reportType:1-举报人；2-举报微句；3-举报评论
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(ChatViewActivity.this,LoginActivity.class);
            startActivity(intent);
            return;
        }
        Intent intent = new Intent(ChatViewActivity.this, ReportActivity.class);
        intent.putExtra(APIKey.idKey,reportId);
        intent.putExtra(APIKey.typeKey,reportType);
        startActivity(intent);
    }

    private void black(final String state){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("state", state);
        map.put("userid", target.getFromuserid());
        String url = "miniapp/letter/"+"langappid"+"/black.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    PeopledbModel p = PeopledbService.getOneData(target.getUserid(), target.getFromuserid());
                    if (state.equals("1")){
                        if (p != null){
                            p.setType(LetterConstant.sx_black_people);
                        }else {
                            p = new PeopledbModel();
                            p.setType(LetterConstant.sx_black_people);
                            p.setUserid(target.getUserid());
                            p.setFromuserid(target.getFromuserid());
                            p.setTime((int)(System.currentTimeMillis()/1000));
                            p.setRemark("");
                            p.setHeader(target.getHeader());
                            p.setNickname(target.getNickname());
                        }
                        PeopledbService.saveOrUpdate(p);
                    }else {
                        if (p != null){
                            PeopledbService.deleteById(p.getId());
                        }
                    }
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.print("活动返回了\n");
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    //将保存在本地的图片取出并缩小后显示在界面上
                    Bitmap bitmap = BitmapFactory.decodeFile(CommonUtils.getFile(Environment.DIRECTORY_PICTURES)+"/image.jpg");
                    Bitmap newBitmap = zoomBitmap(bitmap, bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
                    //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
                    bitmap.recycle();
                    //将处理过的图片显示在界面上，并保存到本地
                    //iv_image.setImageBitmap(newBitmap);
                    //savePhotoToSDCard(Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()), newBitmap);
                    //sendImageMessage(newBitmap);
                    break;
                case CHOOSE_PICTURE:
                    if (data != null) {
                        //ArrayList<String> photos =
                                //data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                        /*
                        ArrayList<String> photos =
                                data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                        for(String string : photos){
                            System.out.print(string+"\n");
                            //sendImageMessage(string);
                        }
                        */
                        /*
                        ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                        if (resultPhotos != null && resultPhotos.size() > 0){
                            Photo photo = resultPhotos.get(0);
                            imageUri = getUriFromFile(CustomApplication.mContext,new File(photo.path));
                            cropImage(imageUri);
                        }
                        */
                    }
                    break;
                case CHOOSE_CARD:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        String userid = bunde.getString(APIKey.useridKey);
                        String nickname = bunde.getString(APIKey.nicknameKey);
                        String header = bunde.getString(APIKey.headerKey);
                        //sendCardMessage(userid,nickname,header);
                    }
                    break;
                case CHOOSE_GOODS:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        String goodsid = bunde.getString(APIKey.goodsidKey);
                        String goodsname = bunde.getString(APIKey.goodsnameKey);
                        String goodsheader = bunde.getString(APIKey.goodssamllpicKey);
                        //sendGoodsMessage(goodsid,goodsname,goodsheader);
                    }
                    break;
                case Private_Red:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        String redid = bunde.getString(APIKey.redidKey);
                        String type = Constant.privateRedType+"";
                        String time = bunde.getString(APIKey.timeKey);
                        String content = bunde.getString(APIKey.contentKey);
                        //sendRedMessage(redid,content,type,time);
                    }
                    break;
                case Common_Red:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        String redid = bunde.getString(APIKey.redidKey);
                        String type = bunde.getString(APIKey.typeKey);;
                        String time = bunde.getString(APIKey.timeKey);
                        String content = bunde.getString(APIKey.contentKey);
                        //sendRedMessage(redid,content,type,time);
                    }
                    break;
                case Guess_Red:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        String redid = bunde.getString(APIKey.redidKey);
                        String type = bunde.getString(APIKey.typeKey);;
                        String time = bunde.getString(APIKey.timeKey);
                        String content = bunde.getString(APIKey.contentKey);
                        //sendRedMessage(redid,content,type,time);
                    }
                    break;
                case Prize_Red:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        String redid = bunde.getString(APIKey.redidKey);
                        String type = bunde.getString(APIKey.typeKey);;
                        String time = bunde.getString(APIKey.timeKey);
                        String content = bunde.getString(APIKey.contentKey);
                        //sendRedMessage(redid,content,type,time);
                    }
                    break;
                case Select_Location:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        double longitude = bunde.getDouble(APIKey.longtitudeKey,0.0f);
                        double latitude = bunde.getDouble(APIKey.latitudeKey,0.0f);
                        String location = bunde.getString(APIKey.locationKey);
                        String url = bunde.getString(APIKey.urlKey);
                        if (!CommonUtils.isEmpty(location)){
                            //sendLocationMessage(longitude,latitude,location,url);
                        }
                    }
                    break;
                case UserInfo:
                    if (data != null){
                        Bundle bunde = data.getExtras();
                        String name = bunde.getString(APIKey.nameKey);
                        String userid = bunde.getString(APIKey.useridKey);
                        String header = bunde.getString(APIKey.headerKey);
                        dealWithUserInfo(userid,header,name,true);
                        chattingListAdapter.notifyDataSetChanged();
                    }
                    break;
                case Update_Pic:
                    finish();
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        ekBar.reset();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //MediaPlayerManager.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void loadMore(){

        List<LetterdbModel> messages = LetterdbService.getChat(target.getUserid(), target.getFromuserid(), pageIndex, LetterConstant.MaxReadNumber);
        if (messages != null && messages.size() > 0){
            pageIndex += messages.size();
            List<LetterdbModel> data = new ArrayList<>();
            for (LetterdbModel m : messages){
                if (m.isCancel() == true){
                    if (m.getIsSelf() == 1){
                        m.setExtra("你撤回了一条消息");
                    }else {
                        m.setExtra("对方撤回了一条消息");
                    }
                    m.setType(LetterConstant.sx_timeMsg);
                }else {
                    if (m.getType() == LetterConstant.sx_textMsg){

                    }else if (m.getType() == LetterConstant.sx_timeMsg){

                    }else {
                        m.setExtra("未知消息，请升级到最新版本查看");
                        m.setType(LetterConstant.sx_timeMsg);
                    }
                }
                data.add(m);
                if (lastMessageTime - m.getTime() > LetterConstant.sx_msg_timeout){
                    LetterdbModel timeData = new LetterdbModel();
                    timeData.setType(LetterConstant.sx_timeMsg);
                    timeData.setExtra(DateUtil.getChatDate(m.getTime()));
                    data.add(timeData);
                }
                lastMessageTime = m.getTime();
            }
            lvChat.stopRefresh(true);
            if (messages.size() < LetterConstant.MaxReadNumber){
                lvChat.setPullRefreshEnable(false);
            }
            chattingListAdapter.insertDataList(data);
        }else {
            lvChat.setPullRefreshEnable(false);
            lvChat.stopRefresh(true);
        }

    }

    private void clickBack(){
        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(LetterConstant.InChatKey, "");
        LetterdbService.changeToSendFailState(target.getUserid(), target.getFromuserid());
        LetterdbService.changeToReadState(target.getUserid(), target.getFromuserid());
        LetterdbModel m = LetterdbService.getByMsgId(target.getUserid()+target.getFromuserid());
        if (m != null){
            m.setUnReadCount(0);
            LetterdbService.saveOrUpdate(m);
        }
        Intent mIntent = new Intent(BroadcastDefine.Update_MsgCount_Action);
        //发送广播
        CustomApplication.mContext.sendBroadcast(mIntent);
        finish();
    }

    //返回按键监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            clickBack();
        }

        return false;

    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        clickBack();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void initView() {
        initEmoticonsKeyBoardBar();
        initListView();
    }


    private void initEmoticonsKeyBoardBar() {
        SimpleCommonUtils.initEmoticonsEditText(ekBar.getEtChat());

        ekBar.setAdapter(SimpleCommonUtils.getCommonAdapter(this, emoticonClickListener));

        ekBar.addFuncView(new SimpleAppsGridView(this));

        ekBar.addOnFuncKeyBoardListener(this);


        ekBar.getEtChat().setOnSizeChangedListener(new EmoticonsEditText.OnSizeChangedListener() {
            @Override
            public void onSizeChanged(int w, int h, int oldw, int oldh) {
                scrollToBottom();
            }
        });
        ekBar.getEtChat().setTextColor(getResources().getColor(R.color.defaultFontColor));
        ekBar.getEtChat().addTextChangedListener(new Watcher(ekBar.getEtChat()));

        ekBar.getBtnSend().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnSendBtnClick(ekBar.getEtChat().getText().toString());
                ekBar.getEtChat().setText("");
            }
        });


        ekBar.getBtnVoice().setVisibility(View.GONE);
        ekBar.setBackgroundColor(Color.parseColor("#F5F7FA"));
        /*
        ekBar.getEmoticonsFuncView().setVisibility(View.GONE);
        ekBar.getEmoticonsToolBarView().setVisibility(View.GONE);
        ekBar.getEmoticonsIndicatorView().setVisibility(View.GONE);
        */

        /*
        ekBar.getBtnVoice().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //return mAudioRecorderButton.onTouch(v,event);
                return false;
            }
        });

        ekBar.getEmoticonsToolBarView().addFixedToolItemView(false, R.mipmap.icon_add, null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(ChatViewActivity.this, "ADD", Toast.LENGTH_SHORT).show();
                //???
            }
        });
        ekBar.getEmoticonsToolBarView().addToolItemView(R.mipmap.icon_setting, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(ChatViewActivity.this, "SETTING", Toast.LENGTH_SHORT).show();
                //???
            }
        });


        ekBar.addOnFuncKeyBoardListener(new FuncLayout.OnFuncKeyBoardListener() {
            @Override
            public void OnFuncPop(int i) {
                System.out.print("点击了"+i+"\n");
            }

            @Override
            public void OnFuncClose() {

            }
        });
        */

    }

    EmoticonClickListener emoticonClickListener = new EmoticonClickListener() {
        @Override
        public void onEmoticonClick(Object o, int actionType, boolean isDelBtn) {
            System.out.print("点击了onEmoticonClick\n");
            if (isDelBtn) {
                SimpleCommonUtils.delClick(ekBar.getEtChat());
            } else {
                if(o == null){
                    return;
                }
                if(actionType == Constants.EMOTICON_CLICK_BIGIMAGE){
                    if(o instanceof EmoticonEntity){
                        OnSendImage(((EmoticonEntity)o).getIconUri());
                    }
                } else {
                    String content = null;
                    if(o instanceof EmojiBean){
                        content = ((EmojiBean)o).emoji;
                    } else if(o instanceof EmoticonEntity){
                        content = ((EmoticonEntity)o).getContent();
                    }

                    if(TextUtils.isEmpty(content)){
                        return;
                    }
                    int index = ekBar.getEtChat().getSelectionStart();
                    Editable editable = ekBar.getEtChat().getText();
                    editable.insert(index, content);
                }
            }
        }
    };

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //System.out.print("dispatchKeyEvent\n");
        if(EmoticonsKeyboardUtils.isFullScreen(this)){
            boolean isConsum = ekBar.dispatchKeyEventInFullScreen(event);
            return isConsum ? isConsum : super.dispatchKeyEvent(event);
        }
        return super.dispatchKeyEvent(event);
    }

    private void initListView() {
        chattingListAdapter = new ChatViewAdapter(ChatViewActivity.this);
        lvChat.setAdapter(chattingListAdapter);
        lvChat.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case SCROLL_STATE_FLING:
                        break;
                    case SCROLL_STATE_IDLE:
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                        ekBar.reset();
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        chattingListAdapter.setUserInfo(target.getUserid(),CustomApplication.loginModel.getThumbheader(),CustomApplication.loginModel.getNickname());
        chattingListAdapter.setUserInfo(target.getFromuserid(),target.getHeader(),target.getNickname());
        getHistoryMessage();//有问题
    }

    private void OnSendBtnClick(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            sendTextMsg(msg);
            //System.out.print("发送文本消息\n");
        }
    }

    private void OnSendImage(String image) {
        if (!TextUtils.isEmpty(image)) {
            OnSendBtnClick("[img]" + image);
        }
        //System.out.print("键盘：OnSendImage\n");
    }

    private void scrollToBottom() {
        lvChat.requestLayout();
        lvChat.post(new Runnable() {
            @Override
            public void run() {
                lvChat.setSelection(lvChat.getBottom());
            }
        });
        //System.out.print("键盘：scrollToBottom\n");
    }

    @Override
    public void OnFuncPop(int height) {
        scrollToBottom();
        ekBar.getBtnVoice().setVisibility(View.GONE);
        System.out.print(height+"键盘：OnFuncPop\n");
    }

    @Override
    public void OnFuncClose() {
        System.out.print("键盘：OnFuncClose\n");
        ekBar.getBtnVoice().setVisibility(View.GONE);
    }


    public class Watcher implements TextWatcher
    {
        private EditText EditID = null;
        public Watcher(EditText id){
            EditID = id;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            /*
            if (conversationType == Conversation.ConversationType.GROUP){
                if (EditID.getText().length() == 1){
                    if (EditID.getText().toString().equals("@")){
                        ekBar.reset();
                        Intent intent = new Intent(ChatViewActivity.this,AtPeopleActivity.class);
                        intent.putExtra(APIKey.groupidKey,targetId);
                        intent.putExtra(APIKey.typeKey,1);
                        startActivityForResult(intent,At_Message);
                    }
                }
            }
            */
        }

    }

    /** 缩放Bitmap图片 **/
    public Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    /**拍照获取相片**/
    private void doTakePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
        Uri imageUri = Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //直接使用，没有缩小
        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
    }

    //选择图片
    private void selectPhoto(){
        /*
        PhotoPickerIntent intent = new PhotoPickerIntent(ChatViewActivity.this);
        intent.setPhotoCount(1);
        intent.setShowCamera(true);
        startActivityForResult(intent, CHOOSE_PICTURE);
        */
//        PhotoPicker.builder()
//                .setPhotoCount(1)
//                .setShowCamera(true)
//                .setShowGif(false)
//                .setPreviewEnabled(false)
//                .start(ChatViewActivity.this, CHOOSE_PICTURE);//PhotoPicker.REQUEST_CODE
        EasyPhotos.createAlbum(this, false, GlideEngine.getInstance())
                .start(CHOOSE_PICTURE);
    }

    //失败的消息重新发送
    public void resendMessage(final LetterdbModel chatData, final int position){

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("msg", chatData.getContent());
        map.put("msgId", chatData.getMsgId());
        map.put("userid", target.getFromuserid());
        String url = "miniapp/letter/"+"langappid"+"/send.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    SXSendResult result = GsonTools.getSXSendResult(data);
                    chatData.setState(LetterConstant.sx_normal_state);
                    chatData.setId(result.getId());
                    chatData.setTime(System.currentTimeMillis());
                    LetterdbService.saveOrUpdate(chatData);
                    saveConversation(chatData);
                    chattingListAdapter.mData.remove(chatData);
                    chattingListAdapter.mData.add(chatData);
                    chattingListAdapter.notifyDataSetChanged();
                    scrollToBottom();
                }else {
                    chatData.setState(LetterConstant.sx_normal_state);
                    chatData.setExtra(commonModel.getMsg());
                    chatData.setType(LetterConstant.sx_timeMsg);
                    LetterdbService.saveOrUpdate(chatData);
                    chattingListAdapter.updateData(position,chatData);
                }
            }

            @Override
            public void onError(String msg) {
                chatData.setState(LetterConstant.sx_sendFail_state);
                LetterdbService.saveOrUpdate(chatData);
                chattingListAdapter.updateData(position,chatData);
            }
        });

    }

    //保存会话
    private void saveConversation(LetterdbModel chatData){
        if (chatData != null){
            LetterdbModel conversation = new LetterdbModel();
            conversation.setId(chatData.getId());
            conversation.setExtra(chatData.getExtra());
            conversation.setTime(chatData.getTime());
            conversation.setType(chatData.getType());
            conversation.setCancel(chatData.isCancel());
            conversation.setContent(chatData.getContent());
            conversation.setFromuserid(target.getFromuserid());
            conversation.setUserid(target.getUserid());
            conversation.setHeader(target.getHeader());
            conversation.setNickname(target.getNickname());
            conversation.setIsFirst(1);
            conversation.setIsSelf(1);
            conversation.setMsgId(chatData.getMsgId());
            conversation.setRead(true);
            conversation.setState(chatData.getState());
            conversation.setUnReadCount(chatData.getUnReadCount());
            LetterdbService.updateConversation(conversation, false);
        }

    }


    //发送文本消息
    private void sendTextMsg(String msg){
        sendTimeControl();
        final String msgId = CommonUtils.getUUID();
        final int currentIndex = chattingListAdapter.getCurrentCount();
        final LetterdbModel chatData = new LetterdbModel();
        chatData.setUserid(target.getUserid());
        chatData.setFromuserid(target.getFromuserid());
        chatData.setNickname(CustomApplication.loginModel.getNickname());
        chatData.setHeader(CustomApplication.loginModel.getHeader());
        chatData.setId(0);
        chatData.setMsgId(msgId);
        chatData.setContent(msg);
        chatData.setType(LetterConstant.sx_textMsg);
        chatData.setTime(System.currentTimeMillis());
        chatData.setCancel(false);
        chatData.setRead(true);
        chatData.setState(LetterConstant.sx_sending_state);
        chatData.setExtra("");
        chatData.setIsFirst(0);
        chatData.setUnReadCount(0);
        chatData.setIsSelf(1);
        LetterdbService.saveOrUpdate(chatData);
        saveConversation(chatData);
        chattingListAdapter.addData(chatData);
        chattingListAdapter.updateData(currentIndex,chatData);
        scrollToBottom();

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("msg", msg);
        map.put("msgId", msgId);
        map.put("userid", target.getFromuserid());
        String url = "miniapp/letter/"+"langappid"+"/send.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    SXSendResult result = GsonTools.getSXSendResult(data);
                    chatData.setMsgId(result.getMsgId());
                    chatData.setState(LetterConstant.sx_normal_state);
                    chatData.setId(result.getId());
                    LetterdbService.saveOrUpdate(chatData);
                    saveConversation(chatData);
                    chattingListAdapter.updateData(currentIndex,chatData);
                }else {
                    if (commonModel.getCode().equals(Constant.UserReturnCode.CODE_10011)){
                        chatData.setState(LetterConstant.sx_sendFail_state);
                        LetterdbService.saveOrUpdate(chatData);
                        saveConversation(chatData);
                        CustomApplication.showTip(commonModel, ChatViewActivity.this);
                    }else {
                        chatData.setState(LetterConstant.sx_normal_state);
                        chatData.setExtra(commonModel.getMsg());
                        chatData.setType(LetterConstant.sx_timeMsg);
                        LetterdbService.saveOrUpdate(chatData);
                        saveConversation(chatData);
                        chattingListAdapter.updateData(currentIndex,chatData);
                    }

                }
            }

            @Override
            public void onError(String msg) {
                chatData.setState(LetterConstant.sx_sendFail_state);
                LetterdbService.saveOrUpdate(chatData);
                saveConversation(chatData);
                chattingListAdapter.updateData(currentIndex,chatData);
            }
        });

    }

    //发送撤回消息
    private void sendCancleMessage(final int position){
        final LetterdbModel chatData = chattingListAdapter.getIndexData(position);
        if (chatData.getId() > 0){
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("id", chatData.getId()+"");
            map.put("msgId", chatData.getMsgId());
            String url = "miniapp/letter/"+"langappid"+"/cancel.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if (commonModel.getFlag().equals("1")){
                        chatData.setCancel(true);
                        chatData.setExtra("你撤回了一条消息");
                        chatData.setType(LetterConstant.sx_timeMsg);
                        LetterdbService.saveOrUpdate(chatData);
                        if (position == chattingListAdapter.mData.size()- 1){
                            saveConversation(chatData);
                        }
                        chattingListAdapter.updateData(position,chatData);
                    }

                }

                @Override
                public void onError(String msg) {

                }
            });
        }
    }

    //发送时间控制
    private void sendTimeControl(){
        if (chattingListAdapter.mData != null && chattingListAdapter.mData.size() > 0){
            LetterdbModel chatData = chattingListAdapter.mData.get(chattingListAdapter.mData.size()-1);
            if (chatData.getType() != LetterConstant.sx_timeMsg){
                if (System.currentTimeMillis() - chatData.getTime() > LetterConstant.sx_msg_timeout){
                    LetterdbModel timeData = new LetterdbModel();
                    timeData.setType(LetterConstant.sx_timeMsg);
                    timeData.setExtra(DateUtil.getChatDate(System.currentTimeMillis()));
                    chattingListAdapter.addData(timeData);
                }
            }
        }
    }

    //删除本地回话消息
    private void deleteMessageById(String msgId){
        LetterdbService.deleteByMsgId(msgId);
    }

    //读取历史消息
    private void getHistoryMessage(){
        lastMessageTime = System.currentTimeMillis();

        new Thread(){
            @Override
            public void run() {
                super.run();
                final List<LetterdbModel> messages = LetterdbService.getChat(target.getUserid(), target.getFromuserid(), pageIndex, LetterConstant.FirstMaxReadNumber);
                if (messages != null && messages.size() > 0){
                    pageIndex += messages.size();
                    final List<LetterdbModel> data = new ArrayList<>();
                    for (LetterdbModel m : messages){
                        if (m.isCancel() == true){
                            if (m.getIsSelf() == 1){
                                m.setExtra("你撤回了一条消息");
                            }else {
                                m.setExtra("对方撤回了一条消息");
                            }
                            m.setType(LetterConstant.sx_timeMsg);
                        }else {
                            if (m.getType() == LetterConstant.sx_textMsg){

                            }else if (m.getType() == LetterConstant.sx_timeMsg){

                            }else {
                                m.setExtra("未知消息，请升级到最新版本查看");
                                m.setType(LetterConstant.sx_timeMsg);
                            }
                        }
                        data.add(0,m);
                        if (lastMessageTime - m.getTime() > LetterConstant.sx_msg_timeout){
                            LetterdbModel timeData = new LetterdbModel();
                            timeData.setType(LetterConstant.sx_timeMsg);
                            timeData.setExtra(DateUtil.getChatDate(m.getTime()));
                            data.add(0,timeData);
                        }
                        lastMessageTime = m.getTime();
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (messages.size() < LetterConstant.FirstMaxReadNumber){
                                lvChat.setPullRefreshEnable(false);
                            }
                            if (newCount > 10){
                                if (newCount < LetterConstant.FirstMaxReadNumber){
                                    scrollIndex = data.size()-newCount;
                                }
                                moreMessage.setVisibility(View.VISIBLE);
                                moreButton.setText(newCount+"条未读消息");
                            }
                            chattingListAdapter.addDataList(data);
                            scrollToBottom();
                        }
                    });

                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            lvChat.setPullRefreshEnable(false);
                        }
                    });

                }
            }
        }.start();



    }

    class MyHandler extends Handler {
        //默认构造函数
        public MyHandler(){
            super();
        }

        //带有Looper参数的构造函数
        public MyHandler(Looper L){
            super(L);
        }

        //子类重写次方法，处理消息
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            if (msg.obj.toString().equals(HandlerDefine.receivechatmsg_msg)){
                chattingListAdapter.notifyDataSetChanged();
                scrollToBottom();
            }else if (msg.obj.toString().equals(HandlerDefine.select_picture_msg)){
                ekBar.reset();
                selectPhoto();
            }else if (msg.obj.toString().equals(HandlerDefine.take_picture_msg)){
                ekBar.reset();
                doTakePhoto();
            }else if (msg.obj.toString().equals(HandlerDefine.location_msg)){
                ekBar.reset();
                //Intent intent = new Intent(ChatViewActivity.this, SelectLocationActivity.class);
                //startActivityForResult(intent,Select_Location);
            }else if (msg.obj.toString().equals(HandlerDefine.person_card_msg)){
                ekBar.reset();
                //Intent intent = new Intent(ChatViewActivity.this,CardActivity.class);
                //startActivityForResult(intent,CHOOSE_CARD);
            }else if (msg.obj.toString().equals(HandlerDefine.recommend_goods_msg)){
                ekBar.reset();
                /*
                if(CustomApplication.centerName.equals("积分")){
                    Intent intent = new Intent(CustomApplication.mContext, JifenGoodsActivity.class);
                    intent.putExtra(APIKey.typeKey,1);
                    startActivityForResult(intent,CHOOSE_GOODS);
                }else {
                    Intent intent = new Intent(ChatViewActivity.this,GroupGoodsActivity.class);
                    startActivityForResult(intent,CHOOSE_GOODS);
                }
                */

            }else if (msg.obj.toString().equals(HandlerDefine.red_msg)){
                /*
                if (conversationType == Conversation.ConversationType.CHATROOM
                        || conversationType == Conversation.ConversationType.CUSTOMER_SERVICE){
                    ToastUtil.show(ChatViewActivity.this,"本团仅供聊天交流，不能发送红包");
                    return;
                }
                ekBar.reset();
                if (conversationType == Conversation.ConversationType.PRIVATE){
                    Intent intent = new Intent(ChatViewActivity.this,RedPacketActivity.class);
                    startActivityForResult(intent,Private_Red);
                }else{
                    Intent intent = new Intent(ChatViewActivity.this,GroupRedPacketActivity.class);
                    if (conversationType == Conversation.ConversationType.GROUP){
                        intent.putExtra(APIKey.groupidKey,targetId);
                    }
                    startActivityForResult(intent,Common_Red);
                }
                */
                //ToastUtil.show(ChatViewActivity.this,"该功能尚未开放哦");
            }else if (msg.obj.toString().equals(HandlerDefine.guess_red_msg)){
                /*
                if (conversationType == Conversation.ConversationType.CHATROOM
                        || conversationType == Conversation.ConversationType.CUSTOMER_SERVICE){
                    ToastUtil.show(ChatViewActivity.this,"本团仅供聊天交流，不能发送红包");
                    return;
                }
                ekBar.reset();
                Intent intent = new Intent(ChatViewActivity.this,GuessRedPacketActivity.class);
                startActivityForResult(intent,Guess_Red);
                */
                //ToastUtil.show(ChatViewActivity.this,"该功能尚未开放哦");
            }else if (msg.obj.toString().equals(HandlerDefine.rand_red_msg)){
                /*
                if (conversationType == Conversation.ConversationType.CHATROOM
                        || conversationType == Conversation.ConversationType.CUSTOMER_SERVICE){
                    ToastUtil.show(ChatViewActivity.this,"本团仅供聊天交流，不能发送红包");
                    return;
                }
                ekBar.reset();
                Intent intent = new Intent(ChatViewActivity.this,RandRedPacketActivity.class);
                if (conversationType == Conversation.ConversationType.GROUP){
                    intent.putExtra(APIKey.groupidKey,targetId);
                }
                startActivityForResult(intent,Prize_Red);
                */
                //ToastUtil.show(ChatViewActivity.this,"该功能尚未开放哦");
            }else if (msg.obj.toString().equals(HandlerDefine.clear_conversation)){
                chattingListAdapter.clearData();
            }else if (msg.obj.toString().equals(HandlerDefine.sendpicmsg)){//发送图片表情
                ekBar.reset();
                //sendPicMessage();
            }
        }
    }

    //处理撤回消息
    private void updateCancleMessage(final LetterdbModel message){
        //System.out.print(message.getMessageId()+":处理撤回消息\n");
        //子线程
        new Thread(){
            @Override
            public void run() {
                //在子线程中进行下载操作
                if (chattingListAdapter.mData != null && chattingListAdapter.mData.size() > 0){
                    for (int i = 0; i < chattingListAdapter.mData.size(); i++){
                        final LetterdbModel chatData = chattingListAdapter.mData.get(i);
                        final int index = i;
                        if (message.getId() == chatData.getId()){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    chatData.setType(LetterConstant.sx_timeMsg);
                                    chatData.setExtra("对方撤回了一条消息");
                                    chattingListAdapter.mData.set(index,chatData);
                                    LetterdbService.saveOrUpdate(chatData);
                                    android.os.Message msg = new android.os.Message();
                                    msg.obj = new String(HandlerDefine.receivechatmsg_msg);
                                    ChatViewActivity.this.myHandler.sendMessage(msg);
                                }
                            });
                            break;
                        }
                    }
                }
            }
        }.start();
    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("TAG","onReceive接收到聊天广播了："+action);
            if (action.equals(LetterConstant.SXChatNotify)){
                String msgId = intent.getStringExtra("msgId");
                if (!CommonUtils.isEmpty(msgId)){
                    final LetterdbModel chatData = LetterdbService.getByMsgId(msgId);
                    if (chatData != null){
                        if (chatData.isCancel() == true){
                            updateCancleMessage(chatData);
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    chattingListAdapter.addData(chatData);
                                    android.os.Message msg = new android.os.Message();
                                    msg.obj = new String(HandlerDefine.receivechatmsg_msg);
                                    ChatViewActivity.this.myHandler.sendMessage(msg);
                                }
                            });
                        }
                    }
                }
            }else if (action.equals(BroadcastDefine.Select_Picture_Action)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.select_picture_msg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Take_Picture_Action)){
                PermissionUtils.showCamaraNote(ChatViewActivity.this, new PermissionCallback() {
                    @Override
                    public void onResult(boolean flag, boolean showAlert) {
                        if (flag == true){
                            if (PermissionUtils.cameraIsCanUse() == true){
                                android.os.Message msg = new android.os.Message();
                                msg.obj = new String(HandlerDefine.take_picture_msg);
                                ChatViewActivity.this.myHandler.sendMessage(msg);
                            }else {
                                ActivityCompat.requestPermissions(ChatViewActivity.this,
                                        new String[]{Manifest.permission.CAMERA},
                                        1);
                            }
                        }
                    }
                });

            }else if (action.equals(BroadcastDefine.Location_Action)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.location_msg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Person_Card_Action)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.person_card_msg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Recommend_Goods_Action)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.recommend_goods_msg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Red_Action)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.red_msg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Guess_Red_Action)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.guess_red_msg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Rand_Red_Action)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.rand_red_msg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if (action.equals(BroadcastDefine.Group_Report_Update)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.group_report_update);
                ChatViewActivity.this.myHandler.sendMessage(msg);
                sendTextMsg(intent.getStringExtra(APIKey.contentKey));
            }else if (action.equals(BroadcastDefine.Clear_Conversation)){
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.clear_conversation);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }else if(action.equals(BroadcastDefine.SendPicMsg)){
                sendPicUrl = intent.getStringExtra(APIKey.contentKey);
                android.os.Message msg = new android.os.Message();
                msg.obj = new String(HandlerDefine.sendpicmsg);
                ChatViewActivity.this.myHandler.sendMessage(msg);
            }

        }

    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.Receive_ChatMsg_Action);
        myIntentFilter.addAction(BroadcastDefine.Select_Picture_Action);
        myIntentFilter.addAction(BroadcastDefine.Take_Picture_Action);
        myIntentFilter.addAction(BroadcastDefine.Location_Action);
        myIntentFilter.addAction(BroadcastDefine.Person_Card_Action);
        myIntentFilter.addAction(BroadcastDefine.Recommend_Goods_Action);
        myIntentFilter.addAction(BroadcastDefine.Red_Action);
        myIntentFilter.addAction(BroadcastDefine.Guess_Red_Action);
        myIntentFilter.addAction(BroadcastDefine.Rand_Red_Action);
        myIntentFilter.addAction(BroadcastDefine.Group_Report_Update);
        myIntentFilter.addAction(BroadcastDefine.Clear_Conversation);
        myIntentFilter.addAction(BroadcastDefine.SendPicMsg);

        myIntentFilter.addAction(LetterConstant.SXChatNotify);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }


    //长按菜单
    private void popWindow(View parentView, List<String> names, int position){
        if (names == null || names.size() == 0){
            return;
        }
        LayoutInflater inflater = LayoutInflater.from(this);//获取一个填充器
        View view = inflater.inflate(R.layout.menu_pop_window, null);//填充我们自定义的布局
        Button button1 = (Button)view.findViewById(R.id.button1);
        Button button2 = (Button)view.findViewById(R.id.button2);
        Button button3 = (Button)view.findViewById(R.id.button3);
        Button button4 = (Button)view.findViewById(R.id.button4);
        Button button5 = (Button)view.findViewById(R.id.button5);
        Button button6 = (Button)view.findViewById(R.id.button6);
        if (names.size() == 1){
            button2.setVisibility(View.GONE);
            button3.setVisibility(View.GONE);
            button4.setVisibility(View.GONE);
            button5.setVisibility(View.GONE);
            button6.setVisibility(View.GONE);
            button1.setText(names.get(0));
            button1.setTag(position);
            button1.setOnClickListener(this);
        }else if (names.size() == 2){
            button3.setVisibility(View.GONE);
            button4.setVisibility(View.GONE);
            button5.setVisibility(View.GONE);
            button6.setVisibility(View.GONE);
            button1.setText(names.get(0));
            button1.setTag(position);
            button2.setText(names.get(1));
            button2.setTag(position);
            button1.setOnClickListener(this);
            button2.setOnClickListener(this);
        }else if (names.size() == 3){
            button4.setVisibility(View.GONE);
            button5.setVisibility(View.GONE);
            button6.setVisibility(View.GONE);
            button1.setText(names.get(0));
            button1.setTag(position);
            button2.setText(names.get(1));
            button2.setTag(position);
            button3.setText(names.get(2));
            button3.setTag(position);
            button1.setOnClickListener(this);
            button2.setOnClickListener(this);
            button3.setOnClickListener(this);
        }else if (names.size() == 4){
            button5.setVisibility(View.GONE);
            button6.setVisibility(View.GONE);
            button1.setText(names.get(0));
            button1.setTag(position);
            button2.setText(names.get(1));
            button2.setTag(position);
            button3.setText(names.get(2));
            button3.setTag(position);
            button4.setText(names.get(3));
            button4.setTag(position);
            button1.setOnClickListener(this);
            button2.setOnClickListener(this);
            button3.setOnClickListener(this);
            button4.setOnClickListener(this);
        }else if (names.size() == 5){
            button6.setVisibility(View.GONE);
            button1.setText(names.get(0));
            button1.setTag(position);
            button2.setText(names.get(1));
            button2.setTag(position);
            button3.setText(names.get(2));
            button3.setTag(position);
            button4.setText(names.get(3));
            button4.setTag(position);
            button5.setText(names.get(4));
            button5.setTag(position);
            button1.setOnClickListener(this);
            button2.setOnClickListener(this);
            button3.setOnClickListener(this);
            button4.setOnClickListener(this);
            button5.setOnClickListener(this);
        }else if (names.size() == 6){
            button1.setText(names.get(0));
            button1.setTag(position);
            button2.setText(names.get(1));
            button2.setTag(position);
            button3.setText(names.get(2));
            button3.setTag(position);
            button4.setText(names.get(3));
            button4.setTag(position);
            button5.setText(names.get(4));
            button5.setTag(position);
            button6.setText(names.get(5));
            button6.setTag(position);
            button1.setOnClickListener(this);
            button2.setOnClickListener(this);
            button3.setOnClickListener(this);
            button4.setOnClickListener(this);
            button5.setOnClickListener(this);
            button6.setOnClickListener(this);
        }
        Display display = getWindowManager().getDefaultDisplay();//得到当前屏幕的显示器对象
        Point size = new Point();//创建一个Point点对象用来接收屏幕尺寸信息
        display.getSize(size);//Point点对象接收当前设备屏幕尺寸信息
        int width = size.x;//从Point点对象中获取屏幕的宽度(单位像素)
        int height = size.y;//从Point点对象中获取屏幕的高度(单位像素)
        //Log.v("zxy", "width="+width+",height="+height);//width=480,height=854可知手机的像素是480x854的
        //创建一个PopupWindow对象，第二个参数是设置宽度的，用刚刚获取到的屏幕宽度乘以2/3，取该屏幕的2/3宽度，从而在任何设备中都可以适配，高度则包裹内容即可，最后一个参数是设置得到焦点
        popWindow = new PopupWindow(view, 2*width/3, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());//设置PopupWindow的背景为一个空的Drawable对象，如果不设置这个，那么PopupWindow弹出后就无法退出了
        popWindow.setOutsideTouchable(true);//设置是否点击PopupWindow外退出PopupWindow
        WindowManager.LayoutParams params = getWindow().getAttributes();//创建当前界面的一个参数对象
        params.alpha = 0.8f;//设置参数的透明度为0.8，透明度取值为0~1，1为完全不透明，0为完全透明，因为android中默认的屏幕颜色都是纯黑色的，所以如果设置为1，那么背景将都是黑色，设置为0，背景显示我们的当前界面
        getWindow().setAttributes(params);//把该参数对象设置进当前界面中
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {//设置PopupWindow退出监听器
            @Override
            public void onDismiss() {//如果PopupWindow消失了，即退出了，那么触发该事件，然后把当前界面的透明度设置为不透明
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                getWindow().setAttributes(params);
            }
        });
        //第一个参数为父View对象，即PopupWindow所在的父控件对象，第二个参数为它的重心，后面两个分别为x轴和y轴的偏移量
        popWindow.showAtLocation(parentView, Gravity.CENTER, 0, 0);

    }


    public void onClick(View v){
        if (popWindow != null){
            if (v instanceof Button) {
                popWindow.dismiss();
                Button button = (Button) v;
                dealChatMenu(button.getText().toString(),(int)button.getTag());
            }
        }
    }

    //处理菜单消息
    private void dealChatMenu(String title, int position){
        System.out.print("title="+title+", position="+position+"\n");
        LetterdbModel chatData = chattingListAdapter.getIndexData(position);
        if (chatData != null){
            if (title.equals("转发")){
                /*
                Intent intent = new Intent(ChatViewActivity.this, TransferActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("chatdata", chatData);
                intent.putExtras(bundle);
                startActivity(intent);
                */
            }else if (title.equals("删除")){
                deleteMessageById(chatData.getMsgId());
                if (position > 0){
                    LetterdbModel chatData1 = chattingListAdapter.mData.get(position-1);
                    if (chatData1.getType() == LetterConstant.sx_timeMsg){
                        chattingListAdapter.mData.remove(chatData1);
                    }
                }
                chattingListAdapter.mData.remove(chatData);
                chattingListAdapter.notifyDataSetChanged();
            }else if (title.equals("复制")){
                myClip = ClipData.newPlainText("text", chatData.getContent());
                myClipboard.setPrimaryClip(myClip);
            }else if (title.equals("撤回")){
                sendCancleMessage(position);
            }
        }
    }

    //处理用户信息
    private void dealWithUserInfo(String userid, String header, String name, boolean isUpdate){
        /*
        if (CommonUtils.isEmpty(userid)){
            return;
        }
        if (userid.equals(CustomApplication.loginModel.getUid())){//自己的信息
            chattingListAdapter.setUserInfo(userid,CustomApplication.loginModel.getThumbheader(),CustomApplication.loginModel.getNickname());
            return;
        }
        String mheader = chattingListAdapter.headerMap.get(userid);
        if (CommonUtils.isEmpty(mheader) || isUpdate == true){
            chattingListAdapter.setUserInfo(target.getFromuserid(),target.getHeader(),target.getNickname());
        }
        */

    }

}

